//
//  UIColor+OAKit.m
//  OAKitDemo
//
//  Created by ChenJie on 8/24/20.
//  Copyright © 2020 Mist. All rights reserved.
//

#import "UIColor+OAKit.h"

#define kDefaultColor [UIColor blackColor]

@implementation UIColor (OAKit)

#pragma mark - Public methods

/* hex string */
+ (instancetype)oa_colorWithHex:(NSString *)hexString {
    return [self oa_colorWithHex:hexString alpha:1];
}

+ (instancetype)oa_colorWithHex:(NSString *)hexString alpha:(CGFloat)alpha {
    
    hexString = [[hexString stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] uppercaseString];
    
    if (hexString.length < 6) {
        return kDefaultColor;
    }
    
    if ([hexString hasPrefix:@"#"]) {
        hexString = [hexString substringFromIndex:1];
    }
    
    if ([hexString hasPrefix:@"0X"]) {
        hexString = [hexString substringFromIndex:2];
    }
    
    if (hexString.length != 6) {
        return kDefaultColor;
    }
    
    NSUInteger hexNumber = [self hexNumberWithString_m1:hexString];
    return [self oa_colorWithHexNumber:hexNumber alpha:alpha];
}

/* hex number */
+ (instancetype)oa_colorWithHexNumber:(NSUInteger)hexNumber {
    return [self oa_colorWithHexNumber:hexNumber alpha:1];
}

+ (instancetype)oa_colorWithHexNumber:(NSUInteger)hexNumber alpha:(CGFloat)alpha {
    
    if (hexNumber > 0xFFFFFF) {
        return kDefaultColor;
    }
    
    NSInteger red = (hexNumber >> 16) & 0xFF;
    NSInteger green = (hexNumber >> 8) & 0xFF;
    NSInteger blue  = hexNumber & 0xFF;
    
    return [self oa_colorWithRed:red green:green blue:blue alpha:alpha];
}

/* rgb */
+ (instancetype)oa_colorWithRed:(NSInteger)red green:(NSInteger)green blue:(NSInteger)blue {
    return [self oa_colorWithRed:red green:green blue:blue alpha:1];
}

+ (instancetype)oa_colorWithRed:(NSInteger)red green:(NSInteger)green blue:(NSInteger)blue alpha:(CGFloat)alpha {
    return [self colorWithRed:red/255.f green:green/255.f blue:blue/255.f alpha:alpha];
}

/* random */
+ (instancetype)oa_randomColor {
    return [self oa_randomColorWithAlpha:1];
}

+ (instancetype)oa_randomColorWithAlpha:(CGFloat)alpha {
    return [self oa_colorWithRed:arc4random() % 256 green:arc4random() % 256 blue:arc4random() % 256 alpha:alpha];
}

#pragma mark - Private methods

/* string to hex, method 1 */
+ (NSUInteger)hexNumberWithString_m1:(NSString *)hexString {
    NSScanner *scanner = [NSScanner scannerWithString:hexString];
    unsigned int hexNumber;
    [scanner scanHexInt:&hexNumber];
    return hexNumber;
}

/* string to hex, method 2 */
+ (NSUInteger)hexNumberWithString_m2:(NSString *)hexString {
    const char *char_str = [hexString cStringUsingEncoding:NSASCIIStringEncoding];
    unsigned int hexNumber;
    sscanf(char_str, "%x", &hexNumber);
    return hexNumber;
}

/* string to hex, method 3 */
+ (NSUInteger)hexNumberWithString_m3:(NSString *)hexString {
    unsigned long hexNumber = strtoul([hexString UTF8String], 0, 16);
    return hexNumber;
}

@end
